package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zzq
 * @Date 2025/10/22 15:36
 */
@Service
public class WechatServiceImpl implements WechatService {


    //小程序ID
    @Value("${wechat.appid}")
    private String appid;

    //小程序密钥
    @Value("${wechat.secret}")
    private String secret;
    //获取手机号API地址
    private static final String POST_PHONE_API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    //小程序登录API地址
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    //获取访问Token的API地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    /**
     * 获取小程序基本参数
     * @return
     */
    public Map<String,Object> getAppConfig(){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        return paramMap;
    }
    /**
     * 获取小程序访问Token
     * @return
     */
    private String getAccessToken(){
        Map<String,Object> paramMap = this.getAppConfig();
        paramMap.put("grant_type","client_credential");

        String accessToken = HttpUtil.get(GET_ACCESS_TOKEN_URL, paramMap);
        if(StringUtils.isBlank(accessToken)){
            throw new BaseException("获取小程序访问Token失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(accessToken);
        return jsonObject.getString("access_token");
    }

    /**
    /**
     * 根据临时凭证码（openId获取专用凭证码）获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String,Object> paramMap = this.getAppConfig();
        paramMap.put("grant_type","authorization_code");
        paramMap.put("js_code",code);

        String result = HttpUtil.get(GET_OPEN_ID_URL, paramMap);
        if(StringUtils.isBlank(result)){
            throw new BaseException("获取openId失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }

    /**
     * 根据临时凭证码（手机号获取专用凭证码，非openId凭证码）获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        Map<String,Object> paramMap = this.getAppConfig();
        paramMap.put("code",code);
        String accessToken = this.getAccessToken();

        String result = HttpUtil.post(POST_PHONE_API_URL + accessToken, paramMap);
        if(StringUtils.isBlank(result)){
            throw new BaseException("获取手机号失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String phoneInfo = jsonObject.getString("phone_info");
        if(StringUtils.isNotBlank(phoneInfo)){
            JSONObject phoneJsonObject = JSONObject.parseObject(phoneInfo);
            return phoneJsonObject.getString("phoneNumber");
        }
        return null;
    }
}
